package com.billing.mvc.controller;

import java.util.Date;
import java.util.List;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.validation.BindingResult;

import com.billing.persistance.entities.BillOwner;
import com.billing.persistance.entities.BillingEntry;
import com.billing.persistance.entities.BillingEntryConcept;
import com.billing.service.IBillOwnerService;
import com.billing.service.IBillingEntryConceptService;
import com.billing.service.IBillingService;
import org.springframework.beans.support.PagedListHolder;

@Controller
public class BillingController {

	@Autowired
	private IBillingService billingService;
	
	@Autowired
	private IBillingEntryConceptService conceptService;
	
	@Autowired
	private IBillOwnerService ownerService;
	
	private PagedListHolder<BillingEntry> entries;
	
    @ModelAttribute("billingEntry")
    public BillingEntry createNewBillingEntry() {
        return new BillingEntry();
    }
    
    @ModelAttribute("billingEntryCriteria")
    public BillingEntry createNewBillingEntryCriteria() {
        return new BillingEntry();
    }
    
    @ModelAttribute("conceptList")
    public List<BillingEntryConcept> getConceptList() {
        return conceptService.getAllEntryConcepts();
    }
    
    @ModelAttribute("ownerList")
    public List<BillOwner> getOwnerList(){
    	return ownerService.getAllOwners();
    }
	
	@RequestMapping("/")
	public String redirectMain(){
		return "redirect:/list";
	}
	
	@RequestMapping("/list")
	public String getList(ModelMap model){
		
		if (entries == null){
			entries = new PagedListHolder<BillingEntry>(billingService.getBillingEntries());
		}
		
		model.addAttribute("billingList", entries);
		//FIXME
		model.addAttribute("urlPrefix", "billing");
		
		return "list";
	}
	
	
	@RequestMapping("/showAddBill")
	public String showAddBill(ModelMap model){
		return "addBill";
	}
	
	@RequestMapping("/addBill")
	public String addBill(@Valid BillingEntry billingEntry, BindingResult result){
   
		if (result.hasErrors()){
			return "addBill";
		}
		
		billingService.addNewBillingEntry(billingEntry);
		// Force reload
		entries = null;
		return "redirect:/list";
	}
	
	@RequestMapping("/deleteBill")
	public String deleteBill(@RequestParam(value="id") Long billingEntryId, ModelMap model){
   
		BillingEntry targetEntry = new BillingEntry();
		targetEntry.setId(billingEntryId);
		billingService.removeBillingEntry(targetEntry);
		
		// Force reload
		entries = null;
		
		return "redirect:/list";
	}
	
	
	
	
	
}
